module ActiveField::ActiveRecord
  #
  # ActiveRecord::Base hook methods
  #
  module ActMethods
    def activate_fields(&block)
      #
      # Append methods to ActiveRecord class
      #
      extend ClassMethods
      include InstanceMethods
      #include ActiveField::Core::InstanceMethods
      
      # (activesupport/lib/active_support/core_ext/class/attribute_accessors.rb)
      cattr_accessor :fields
      
      puts "#{self.class} : #{self}.activate_fields()"
      self.fields = {}
      if block_given?
        # User define his own field
        yield ActiveField::FieldMapper.new self
      else
        # Do your best to autodetect the fields
        ActiveField::FieldMapper.auto_detect self
        #FIXME
        #setup_active_field_mapping
      end
    end
  end
  
  #
  # ActiveRecord::Base class methods, available after activate_fields() is called
  #
  module ClassMethods
    protected
      # 
      # Analyse columns class variable and store mapping. Runned once on startup.
      #
      def setup_active_field_mapping
        #
        # @columns returns an array of ActiveRecord::ConnectionAdapters::[AdapterName]Column objects
        # with the following properties :
        #   @null, @scale, @name, @sql_type, @type, @precision, @primary, @limit, @default
        #
        self.active_field_mapping = {}
        columns.each do |column|
          # Use DateTimeField rather than DatetimeField as class name
          field_class = (column.type == :datetime) ? 'DateTime' : ActiveField::Core.camelize(column.type.to_s)
          begin
            self.active_field_mapping[column.name.to_sym] = eval("ActiveField::Fields::#{field_class}Field")
          rescue NameError #=> e
            puts "WARNING : ActiveField Plugin in model '#{self.to_s}' : '#{field_class}Field' is not implemented yet."
          end
        end
      end
  end
  
  
  #
  # ActiveRecord::Base instance methods, available after activate_fields() is called
  #
  module InstanceMethods
    # 
    # Route the edit request to the proper active field
    #
    def edit( field_name, *args )
      fields[field_name][:class].edit self, field_name, *args
    end
  end
end
